package com.vay.de.dang.online.ui.bill;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.vay.de.dang.online.VnApp;
import com.vay.de.dang.online.entiy.CommodityEntity;
import com.vay.de.dang.online.resp.RApplyBillDto;
import com.vay.de.dang.online.resp.RApplyBillStateDto;
import com.vay.de.dang.online.ui.apply.RecommendActivity;
import com.vay.de.dang.online.util.RequestHelper;
import com.vay.de.dang.online.util.VnHandler;
import com.vay.de.dang.online.util.VnUIManager;
import com.vay.de.dang.online.util.VnUtil;
import com.vay.de.dang.online.view.PullRefreshView;
import com.vay.de.dang.online.web.BillApi;
import com.vay.de.dang.online.web.LoanApi;
import com.vay.de.dang.online.web.ReqCallback;
import com.vay.de.dang.online.web.ReqResult;
import com.vay.de.dang.online.view.DialogBillDetail;
import com.vay.de.dang.online.view.PullRefreshHolder;

import java.util.List;

import com.vay.de.dang.online.R;

public class BillAdapter extends PullRefreshView.RecyclerAdapter<RApplyBillDto> {

    private Activity mActivity;
    private int billType;
    private int pageIndex = 0;
    private int pageSize = 10;
    private boolean hasNext;

    public BillAdapter(Activity activity) {
        mActivity = activity;
    }

    // 状态 0所有 1审核中 2待还款 3已结清
    public void setBillType(int billType) {
        this.billType = billType;
    }

    @Override
    public int getEmptyLayout() {
        return R.layout.view_none;
    }

    @Override
    public void onReload() {
        pageIndex = 0;
        hasNext = false;
        load();
    }

    @Override
    public boolean hasNextPage() {
        return hasNext;
    }

    @Override
    public boolean loadNextPage() {
        pageIndex++;
        return load();
    }

    private boolean load() {
        BillApi.queryBill(billType, pageIndex, new ReqCallback() {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    List<RApplyBillDto> list = (List<RApplyBillDto>) value.result;
                    if (VnUtil.isEmpty(list)) {
                        clear();
                    } else {
                        loadData(list, pageIndex == 0);
                        hasNext = list.size() == 10;
                    }
                }

                resetAll();
            }
        });
        return true;
    }

    @Override
    public int getItemLayout() {
        return R.layout.item_bill_layout;
    }

    @Override
    public void onBindViewHolder(PullRefreshHolder holder, int position) {

        final RApplyBillDto bean = getItem(position);
        RApplyBillStateDto stateLabel = bean.getApplyStateLabel();
        String state = stateLabel.getValue();
        int noShow = bean.getIsControlNoShow();
        int recommend = bean.getRecommend();

        TextView nameTv = holder.findView(R.id.p_name);
        TextView noTv = holder.findView(R.id.p_no);
        TextView repayAmountTv = holder.findView(R.id.repayment_amount_v);
        TextView statusTv = holder.findView(R.id.order_status_v);

        TextView withdrawTv = holder.findView(R.id.bnt_3);
        TextView detailTv = holder.findView(R.id.bnt_2);
        TextView moreTv = holder.findView(R.id.bnt_1);

        nameTv.setText(bean.getCommodityName());
        noTv.setText("No." + bean.getApplyNo());
        repayAmountTv.setText(VnUtil.toMoneyStr1(bean.getFinancialProductsAmount()));
        statusTv.setText(getStateLabel(state));

        // 展示取款码
        if (noShow == 1) {
            withdrawTv.setVisibility(View.VISIBLE);
            detailTv.setVisibility(View.VISIBLE);

            // 详情
            detailTv.setOnClickListener(view -> {
                detailBill(state, bean);
            });

            // 推荐
            checkRecommend(recommend, moreTv);
        } else {

            // 1、审核中 ==> [10 初始状态（待机审）12 机审过（待分配）20 待人审（已分配）30 审批通过（准备放款）31 放款中 32 放款失败]
            // 2、不通过 ==> 11 机审拒 21 人审拒 22 机审再拒
            // 3、已取消 ==>23 人审取消(客户取消) 33 放款取消
            // 4、还款期 ==>40 放款成功(待还款) 42已展期
            // 5、逾期 ==>41 贷款逾期
            // 6、已还清 ==>50 已还清

            // pending: more(推荐商品) , detail (金额，时间，期限)
            // repayment: more, detail(贷款金额，未还金额，应还时间，贷款期限，逾期金额), 还款按钮
            // settle: more, detail(贷款金额，贷款期限，结清时间)

            // 审核中
            if ("1".equals(state)) {
                withdrawTv.setVisibility(View.GONE);
                detailTv.setVisibility(View.VISIBLE);
                moreTv.setVisibility(View.GONE);

                // detail
                detailTv.setOnClickListener(view -> {
                    detailBill(state, bean);
                });

                // 推荐
                checkRecommend(recommend, moreTv);
            }
            // 不通过， 已取消
            else if ("2".equals(state) || "3".equals(state)) {
                withdrawTv.setVisibility(View.GONE);
                detailTv.setVisibility(View.GONE);
                moreTv.setVisibility(View.GONE);
            }
            // 还款期 | 已逾期
            else if ("4".equals(state) || "5".equals(state)) {
                withdrawTv.setVisibility(View.VISIBLE);
                detailTv.setVisibility(View.VISIBLE);

                // 立即还款
                withdrawTv.setText(R.string.bnt_bill_repay_now);
                withdrawTv.setOnClickListener(view -> {
                    Intent intent = new Intent();
                    intent.setClass(mActivity, RepaymentActivity.class);
                    intent.putExtra("applyNo", bean.getApplyNo());
                    mActivity.startActivity(intent);
                });

                // detail
                detailTv.setOnClickListener(view -> {
                    detailBill(state, bean);
                });

                // 推荐
                checkRecommend(recommend, moreTv);

            } else if ("6".equals(state)) {

                withdrawTv.setVisibility(View.VISIBLE);
                detailTv.setVisibility(View.VISIBLE);

                // 重新申请
                withdrawTv.setText(R.string.bnt_bill_re_apply);
                withdrawTv.setOnClickListener(view -> {
                    RequestHelper.requestApplyActivity(mActivity, bean.getCommodityName(),
                            bean.getCommodityNum());
                });

                // detail
                detailTv.setOnClickListener(view -> {
                    detailBill(state, bean);
                });

                // 推荐
                checkRecommend(recommend, moreTv);
            }
        }
    }

    private String getStateLabel(String state) {
        if ("2".equals(state)) {
            return mActivity.getString(R.string.label_bill_state_2);
        } else if ("3".equals(state)) {
            return mActivity.getString(R.string.label_bill_state_3);
        } else if ("4".equals(state)) {
            return mActivity.getString(R.string.label_bill_state_4);
        } else if ("5".equals(state)) {
            return mActivity.getString(R.string.label_bill_state_5);
        } else if ("6".equals(state)) {
            return mActivity.getString(R.string.label_bill_state_6);
        } else {
            return mActivity.getString(R.string.label_bill_state_1);
        }
    }

    private void detailBill(String state, RApplyBillDto bean) {
        new DialogBillDetail(mActivity).showBill(state, bean);
    }

    private void checkRecommend(int recommend, TextView moreTv) {
        if (recommend == 1) {
            moreTv.setVisibility(View.VISIBLE);
            moreTv.setOnClickListener(view -> {
                showRecommend();
            });
        } else {
            moreTv.setVisibility(View.GONE);
            moreTv.setOnClickListener(null);
        }
    }

    private void showRecommend() {
        LoanApi.queryRecommend(new ReqCallback(mActivity) {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    List<CommodityEntity> list = (List<CommodityEntity>) value.result;
                    if (!VnUtil.isEmpty(list)) {
                        RecommendActivity.allData = list;
                        VnUIManager.nextActivity(mActivity, RecommendActivity.class);
                    } else {
                        VnHandler.showText(VnApp.getStr(R.string.label_no_recommend));
                    }
                }
            }
        }.showDialog(true));
    }
}
